<template>
  <div>
    <AplidForm ref="formRef" v-bind="BaseFormConfig" v-model="formModel" @change="handleItemChange" @submit="onSubmit">
    </AplidForm>
  </div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import { ElMessageBox } from 'element-plus'
import { BaseFormConfig } from '../../config'
import { getAreaObj } from '@/utils/util'
import { useCommonStore } from '@/stores/common'
const { setTempParams } = useCommonStore()

const emit = defineEmits(['refresh', 'back'])
const formModel: any = ref({})
const formRef = ref()
const onSubmit = (form, done) => {
  const areaObj: any = getAreaObj(form.areas)
  const areaNameObj: any = getAreaObj(form.areas_name)

  const nowAreasObj: any = getAreaObj(form.nowAreas, 'now')
  const nowAreasNamesObj: any = getAreaObj(form.nowAreasNames, 'now')
  const params = {
    ...form,
    ...areaObj,
    ...areaNameObj,
    ...nowAreasObj,
    ...nowAreasNamesObj,
    areas: undefined,
    areas_name: undefined,
    nowAreas: undefined,
    nowAreasNames: undefined,
    code: 3013,
  }
  setTempParams({
    creditCode: params.creditCode,
    organizationName: params.organizationName,
  })
  apiMod
    .view_dpServiceOrgBase_gather(params)
    .then((res) => {
      emit('refresh', res.data)
      done()
    })
    .catch((err) => {
      done()
    })
}

const openTip = () => {
  ElMessageBox.confirm('数据已采集，统一社会信用代码重复?', '提示', {
    confirmButtonText: '退出',
    cancelButtonText: '重新输入',
    type: 'warning',
  })
    .then(() => {
      emit('back')
    })
    .catch(() => {
      formModel.value.creditCode = undefined
    })
}

const handleItemChange = (model, item, e) => {
  // 校验统一社会信用代码是否已存在
  if (item.prop == 'creditCode') {
    apiMod.view_dpServiceOrgBase_page({ creditCode: e }).then((res) => {
      const data = res.data
      if (data.records.length > 0) {
        openTip()
      }
    })
  }
}

const onSave = () => {
  formRef.value!.onSubmit()
}
defineExpose({
  onSave,
})
</script>

<style scoped></style>
